import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const types = {
  SET_AUTHORIZED: 'SET_AUTHORIZED',
  SET_USER: 'SET_USER'
}

const state = {
  isAuthorized: false,
  user: {}
}

const getters = {
  isAuthorized: state => state.isAuthorized,
  user: state => state.user
}

const mutations = {
  [types.SET_AUTHORIZED](state, isAuthorized) {
    if (isAuthorized) state.isAuthorized = isAuthorized
    else state.isAuthorized = false
  },
  [types.SET_USER](state, user) {
    if (user) state.user = user
    else state.user = {}
  }
}

const actions = {
  setAuthorized: ({ commit }, isAuthorized) => {
    commit(types.SET_AUTHORIZED, isAuthorized)
  },
  setUser: ({ commit }, user) => {
    commit(types.SET_USER, user)
  },
  clearCurrentState: ({ commit }) => {
    commit(types.SET_AUTHORIZED, false)
    commit(types.SET_USER, null)
  }
}

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})
